package com.ktjy.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.ktjy.pojo.TbCourse;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Log4j2
public class ExcelUtil {
    //导出
    public static<T> void exportExcel(List<T> data, String SheetName,Class<T> c,HttpServletResponse response) {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(SheetName);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, c, data);

        //输出流输出给浏览器
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = null;
        try {
            //设置下载文件的名称
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(SheetName, "UTF-8") + ".xlsx");
            out = response.getOutputStream();
            workbook.write(out);
        } catch (Exception e) {
            log.error("SysUserController中exportExcel方法执行报错的。", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    out = null;
                }
            }
        }
    }
}
